package com.uobgroup.ews.uam.core.service;

import com.uobgroup.ews.uam.core.dao.SecurityGroupDao;
import com.uobgroup.ews.uam.core.dao.ldap.LDSDao;
import com.uobgroup.ews.uam.core.domain.SecurityGroup;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly=true)
public class SecurityGroupServiceImpl implements SecurityGroupService {

   @Autowired
   SecurityGroupDao securityGroupDao;

   @Autowired
   LDSDao ldsDao;

   public long countAllSecurityGroups() {
      return securityGroupDao.count();
   }

   public void deleteSecurityGroup(SecurityGroup securityGroup) {
      securityGroupDao.delete(securityGroup);
   }

   public SecurityGroup findSecurityGroup(Long id) {
      return securityGroupDao.findOne(id);
   }

   public List<SecurityGroup> findAllSecurityGroups() {
      return securityGroupDao.findAll();
   }

   public List<SecurityGroup> findSecurityGroupEntries(int firstResult, int maxResults) {
      return securityGroupDao.findAll(firstResult, maxResults);
   }

   @Transactional(readOnly=false, propagation = Propagation.REQUIRED, rollbackFor=Exception.class)
   public void saveSecurityGroup(SecurityGroup securityGroup) {
      String sid = null;
      if (ldsDao.hasGroupByBaseDN(securityGroup.getDisplayName(), securityGroup.getDN()))
         sid = ldsDao.createGroup(securityGroup);
      try {
         securityGroupDao.save(securityGroup);
      }catch (Exception e) {
         if (sid != null){
            ldsDao.deleteGroup(securityGroup);
         }
      }
   }

   public SecurityGroup updateSecurityGroup(SecurityGroup securityGroup) {
      return securityGroupDao.update(securityGroup);
   }

   public boolean hasSecurityGroup(String rolename) {
      SecurityGroup securityGroup = this.securityGroupDao.findName(rolename);
      boolean hasExist = (securityGroup != null);
      return hasExist;
   }

   @Override
   public List<SecurityGroup> findAllSecurityGroupsThatHasNoSegment() {
      return securityGroupDao.findAllSecurityGroupsThatHasNoSegment();
   }
}
